package com.common.allCommon;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Environment;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.TextView;

public class TextHelper {
    private static final String TAG = "TextHelper";
    private static final String HTTP_HEADER="http://";
    private static final String UID_TAG="?uid=";
    private static final String KEY_TAG="&k=";
    private static HashMap<String, String> _userLinkMapping = new HashMap<String, String>();
    private static final Pattern NAME_MATCHER = Pattern.compile("@.+?\\s");
    private static final String TWITTA_USER_URL = "twitta://users/";
    private static final Pattern TAG_MATCHER = Pattern.compile("#\\w+#");
    private static Pattern USER_LINK = Pattern.compile("@<a href=\"http:\\/\\/fanfou\\.com\\/(.*?)\" class=\"former\">(.*?)<\\/a>");
    private static final String TWITTA_SEARCH_URL = "twitta://search/";
    protected static DecimalFormat numFormat = new DecimalFormat("#.#"); 
    
    public static String fileerMsgText(String text){
    	if(isEmpty(text))return "";
    		int index = text.indexOf("");
    	if(index!=-1){
    		return text.substring(0,index);
    	}
    	else return "";
    }
    
    public static String getFliteStr(String str){
		if(str==null||str.equals("null")){
			return "";
		}
		else return str.trim();
	}
    
    public static String getFileLengthUnitKB(long length){
    	return numFormat.format(length/1024.0)+"KB";
    }
    
    public static String changeCharset(String str, String oldCharset, String newCharset)  {
        if(str != null) {
            //用源字符编码解码字符串
            byte[] bs;
			try {
				bs = str.getBytes(oldCharset);
				return new String(bs, newCharset);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
        }
        return "";
    }
    
    /**
     * 判断字符串是否为空字符串和空指针
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        return s == null || s.length() == 0||s.equals("null");
    }
    public static boolean isNotNull(String s) {
        return s == null ||s.equals("null");
    }

    /**
     * 把输入流里面的内容返回字符串
     */
    public static String stringifyStream(InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        return sb.toString();
    }

    private static final Linkify.MatchFilter NAME_MATCHER_MATCH_FILTER = new Linkify.MatchFilter() {
        @Override
        public final boolean acceptMatch(final CharSequence s, final int start,final int end) {
            String name = s.subSequence(start + 1, end).toString().trim();
            boolean result = _userLinkMapping.containsKey(name);
            return result;
        }
    };

    private static final Linkify.TransformFilter NAME_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
        @Override
        public String transformUrl(Matcher match, String url) {
            String name = url.subSequence(1, url.length()).toString().trim();
            return _userLinkMapping.get(name);
        }
    };
    
    
    public static boolean isNull(String s) {
        return s == null;
    }
    
    public static boolean isNullEmpty(String s) {
       return s == null || s.length() == 0;
   }


    public static void linkifyUsers(TextView view) {
        Linkify.addLinks(view, NAME_MATCHER, TWITTA_USER_URL,NAME_MATCHER_MATCH_FILTER, NAME_MATCHER_TRANSFORM_FILTER);
    }

    private static final Linkify.TransformFilter TAG_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
        @Override
        public final String transformUrl(Matcher match, String url) {
			if (url.length() > 1) {
				String result = url.substring(1, url.length() - 1);
				return "%23" + result + "%23";
			} else {
				return "";
			}
        }
    };

    public static void linkifyTags(TextView view) {
        Linkify.addLinks(view, TAG_MATCHER, TWITTA_SEARCH_URL, null,TAG_MATCHER_TRANSFORM_FILTER);
    }
    
    public static String getSimpleHtmlText(String text) {
        return text.replaceAll("<.*?>", "").replace("&lt;", "<")
                .replace("&gt;", ">").replace("&nbsp;", " ")
                .replace("&amp;", "&").replace("&quot;", "\"");
    }

    public static boolean isUrl(String string){
    	if (TextUtils.isEmpty(string)){
    		return false;
    	}
    	String s=string.toLowerCase();
    	return s.contains(HTTP_HEADER);
    }
    
    public static long getUidFromUrl(String data){
		int start=data.indexOf(UID_TAG);
		int end=data.indexOf(KEY_TAG);
		if (start<0 || end<0){
			return 0;
		}
		
		try {
			String uid=data.substring(start+UID_TAG.length(), end);
			long lUid=Long.parseLong(uid);
			return lUid;
		}catch(StringIndexOutOfBoundsException e){
			Log.e(TAG, "get uid index out of bounds");
			e.printStackTrace();
		} catch (Exception e) {

		}
		return 0;
    }
    
    public static boolean isLocalFile(String path){
    	if (TextUtils.isEmpty(path)){
    		return false;
    	}
    	String mntpath=Environment.getExternalStorageDirectory().getAbsolutePath();
    	return path.contains(mntpath);
    }
    
    public static byte[] hexStringToBytes(String hexString) {  
	    if (hexString == null || hexString.equals("")) {  
	        return null;  
	    }  
	    hexString = hexString.toUpperCase();  
	    int length = hexString.length() / 2;  
	    char[] hexChars = hexString.toCharArray();  
	    byte[] d = new byte[length];  
	    for (int i = 0; i < length; i++) {  
	        int pos = i * 2;  
	        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
	    }  
	    return d;  
	}  
	
	private static byte charToByte(char c) {  
	    return (byte) "0123456789ABCDEF".indexOf(c);  
	} 
}
